// 数据采集入口，
const menuItemEntryClass = '.menu-item'
// 追加dom元素根挂载点
const resultItemRootMountPointId = '#result-body'

// 需要传递的数据
let currentMenuItemKey = ''
let currentMenuItemValue = ''

// 保存结果item相关状态
const switchClassName = 'switch-background-color'
const type = {'append':'append', 'before':'item-before', 'after':'item-after', 'edit':'item-edit', 'del': 'item-del'}
const defaultOperationType = 'append'
let currentOperationType = defaultOperationType //核心变量1，保存当前操作状态
let pointer = '' //核心变量2，指针，保存当前操作的DOM元素的id值

//数据结果集
let resultItemObj = {}

window.onload = function () {
    /**
     * 调用组件方式一：通过class="menu-item"绑定
     */
    $(menuItemEntryClass).click(function () {
        const key = $(this).attr('id');
        const value = $(this).text();
        handleEntryParam(key, value)
        handleClickMenuItemClass()
        emptyKeyAndValue()
    })
}

/**
 * 调用组件方式二：显式调用函数
 * @param key
 * @param value
 */
function handleClickMenuItem(key, value) {
    handleEntryParam(key, value)
    handleClickMenuItemClass()
    emptyKeyAndValue()
}
/*使用组件的入口函数 end*/

/*核心函数库 start*/
function handleClickMenuItemClass() {
    println()
    switch (currentOperationType) {
        case type['append']:
            const resultItemDomObj = createResultItemDom();
            resultItemObj[resultItemDomObj['id']] = getObject(resultItemDomObj['key'], resultItemDomObj['value'])
            $(resultItemRootMountPointId).append(resultItemDomObj['resultItem'])
            break
        case type['edit']:
            resultItemObj[pointer] = getObject(currentMenuItemKey, currentMenuItemValue)
            $(`#${pointer}`).text(currentMenuItemValue)
            $(`#${pointer}`).attr('key', currentMenuItemKey)
            break
        default:
            break
    }
}

/**
 * 处理点击结果项
 * @param id
 */
function handleClickResultItem(id) {
    /* 点击的选中元素 */
    if (id === pointer) {
        $(`#${id}`).removeClass(switchClassName)
        pointer = ''
        if (currentOperationType !== type.edit) {
            $(`#${id}op`).slideToggle()
        }
    } else {
        /* 点击的非选中元素 */
        // 操作上次点击的元素
        if (pointer !== '') {
            $(`#${pointer}`).removeClass(switchClassName)
            $(`#${pointer}op`).slideUp()
        }
        // 操作本次点击的元素
        pointer = id
        const that = $(`#${pointer}`)
        that.addClass(switchClassName)
        $(`#${pointer}op`).slideDown()
    }
    currentOperationType = defaultOperationType
    println()
}

/**
 * 处理点击结果操作项
 * @param type
 */
function handleClickResultItemOperation(type) {
    currentOperationType = type
    handleClickResultItemOpItemClass()
}

function handleClickResultItemOpItemClass() {
    println()
    const resultItemDomObj = createResultItemDom();

    switch (currentOperationType) {
        case type['before']:
            $(`#${pointer}div`).before(resultItemDomObj['resultItem'])
            resultItemObj[resultItemDomObj['id']] = ' '
            currentOperationType = defaultOperationType
            break
        case type['after']:
            $(`#${pointer}div`).after(resultItemDomObj['resultItem'])
            resultItemObj[resultItemDomObj['id']] = ' '
            currentOperationType = defaultOperationType
            break
        case type['edit']:
            $(`#${pointer}op`).slideUp()
            break
        case type['del']:
            $(`#${pointer}div`).remove()
            delete resultItemObj[pointer]
            currentOperationType = defaultOperationType
            pointer = ''
            break
        default:
            break
    }
}

/**
 * 创建联动菜单结果项DOM元素
 * @returns {{resultItem: string, id: string, value: string, key: string}}
 */
function createResultItemDom() {
    const key = currentMenuItemKey
    const value = currentMenuItemValue
    const id = 'aden' + new Date().getTime()
    const resultItem =
        `
        <div id="${id}div" class="result-item-div">
            <span class="result-item" id="${id}" key="${key}" onclick="handleClickResultItem(this.id)">${value}</span>
            <div class="result-item-op" id="${id}op">
                <div id="item-before" class="result-item-op-item" onclick="handleClickResultItemOperation(this.id)">前置添加</div>
                <div id="item-after" class="result-item-op-item" onclick="handleClickResultItemOperation(this.id)">后置添加</div>
                <div id="item-edit" class="result-item-op-item" onclick="handleClickResultItemOperation(this.id)">修改</div>
                <div id="item-del" class="result-item-op-item" onclick="handleClickResultItemOperation(this.id)">删除</div>
            </div>
        </div>
        `

    return {key, value, id, resultItem}
}

/**
 * 获取拼接KEY的结果集
 */
function getJointKey() {
    let key = ''
    $(`${resultItemRootMountPointId} span.result-item`).each(function(){
        key += $(this).attr('key') + connector.comma
    });
    return key
}

/**
 * 获取拼接Value的结果集
 */
function getJointValue() {
    let value = ''
    $(`${resultItemRootMountPointId} span.result-item`).each(function(){
        value += $(this).text() + connector.comma
    });
    return value
}

/**
 * 重置
 */
function handleClickReset() {
    resultItemObj = {}
    $(resultItemRootMountPointId).empty()
}
/*核心函数库 end*/

/*工具方法 srart*/
/**
 * 判断字符串是否以某个子串结尾
 * @param string
 * @param endWithStr
 * @returns {boolean}
 */
function endWith(string, endWithStr){
    const d = string.length - endWithStr.length;
    return (d >= 0 && string.lastIndexOf(endWithStr) == d)
}

// 规则处理
const connector = {'semicolon':';', 'colon':':', 'plus':'+', 'comma':','}
const nextGroupFlag = '且'

/**
 * 入参处理，可以在这里转换数据格式等
 * @param text
 * @param key
 * @Param keepRawValue 是否使用原始值
 */
function handleEntryParam(key, value, keepRawValue = true) {
    if (keepRawValue) {
        currentMenuItemKey = key
        currentMenuItemValue = value
    } else {
        currentMenuItemKey = key + connector.plus + connector.colon
        currentMenuItemValue = value + connector.comma
    }
}

/**
 * 清空变量存储的数据
 */
function emptyKeyAndValue() {
    currentMenuItemValue = ''
    currentMenuItemKey = ''
}

/**
 * 返回一个对象
 */
function getObject(key, value) {
    return JSON.parse(`{"${key}":"${value}"}`)
}
/*工具方法 end*/

/*开发阶段函数 start*/
function seeResult() {
    $('#result-key').text(getJointKey())
    $('#result-value').text(getJointValue())
}

/**
 * 打印数据，开发阶段观察数据
 */
function println() {
    console.log(`pointer: ${pointer}`)
    console.log(`currentOperationType: ${currentOperationType}`)
    console.log(resultItemObj)
}
/*开发阶段函数 end*/
